package th.retrofit.lib;

import java.util.LinkedList;
import java.util.Queue;

/**
 * https://leetcode-cn.com/problems/symmetric-tree/
 * 给定一个二叉树，检查它是否是镜像对称的。
 */
public class Solution101 {

    public boolean isSymmetric(TreeNode root) {
        return iSymmetric(root.left, root.right);
    }

    public boolean iSymmetric(TreeNode left, TreeNode right) {
        if (left == null && right == null) return true;
        if (left == null || right == null) return false;
        return left.val == right.val
                && iSymmetric(left.left, right.right)
                && iSymmetric(left.right, right.left);
    }

    public boolean isSymmetric1(TreeNode root) {
        return iSymmetric1(root.left, root.right);
    }

    public boolean iSymmetric1(TreeNode left, TreeNode right) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(left);
        queue.offer(right);
        while (!queue.isEmpty()) {
            TreeNode u = queue.poll();
            TreeNode v = queue.poll();
            if (u == null && v == null) {
                continue;
            }
            if (u == null || v == null || u.val != v.val) {
                return false;
            }
            queue.offer(u.left);
            queue.offer(v.right);
            queue.offer(u.right);
            queue.offer(v.left);
        }
        return true;
    }


    public static void main(String[] args) {
        int[] arr = new int[]{1,2,2,3,4,4,3};
        TreeNode[] nodes = new TreeNode[arr.length];
        for (int i = 0; i < arr.length; i++) {
            nodes[i] = new TreeNode(arr[i]);
        }
        TreeNode root = TreeNode.array2Tree(nodes);
        System.out.println(root);
        System.out.println(new Solution101().isSymmetric(root));
    }

}
